package com.ly.common.running.start;

import com.google.common.eventbus.EventBus;
import com.ly.common.running.annotation.EventListenerAnnotation;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class EventListener implements ApplicationContextAware {
    private static EventBus eventBus = new EventBus();

    public static void postEvent(Object event) {
        eventBus.post(event);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> map = applicationContext.getBeansWithAnnotation(EventListenerAnnotation.class);
        List<Object> listeners = map.entrySet().stream().map(e -> e.getValue()).collect(Collectors.toList());
        //注册监听
        for (Object var : listeners) {
            eventBus.register(var);
        }
    }
}
